from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensions import db
from datetime import datetime
from sqlalchemy import func, text

class CardConsumption(db.Model):
    """消费记录模型"""
    __tablename__ = 'card_consumptions'

    # 自增主键ID，系统内部使用的唯一标识
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
    # 订单ID（自增主键）
    order_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 收支类型（0:支出, 1:收入, 3:流水）流水是指客户消费后，后台自动生成的一条记录，用于记录客户消费的金额或次数，不计入支出收入统计中）
    income_type: Mapped[int] = mapped_column(db.Integer, nullable=False)
    # 收支类型（1:卡包充值, 2:成本支出, 3:现金单次消费, 4:卡包消费, 5:卡包提成, 6:单笔业务提成，7:材料扣款金额，8:材料扣款比例, 9:股东分红,10:平台股东分红 ）
    transaction_type: Mapped[int] = mapped_column(db.Integer, nullable=False)
    # 店铺ID（自增主键）
    store_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 卡包ID（自增主键）
    card_package_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 消费用户ID（自增主键）
    user_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 销售员ID（自增主键）
    staff_id: Mapped[int] = mapped_column(db.Integer, nullable=False)
    # 处理用户ID（操作员ID，可选）
    handle_user_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 产品ID（自增主键）
    product_id: Mapped[Optional[int]] = mapped_column(db.Integer, nullable=True)
    # 消费日期
    consumption_date: Mapped[Optional[datetime]] = mapped_column(db.DateTime, nullable=True)
    
    # 年月日冗余字段，用于快速分组查询
    consumption_day: Mapped[int] = mapped_column(
        db.Integer,
        server_default=text("(DATE_FORMAT(CURRENT_TIMESTAMP, '%Y%m%d') + 0)"),
        default=lambda: int(datetime.now().strftime('%Y%m%d'))
    )
    consumption_month: Mapped[int] = mapped_column(
        db.Integer,
        server_default=text("(DATE_FORMAT(CURRENT_TIMESTAMP, '%Y%m') + 0)"),
        default=lambda: int(datetime.now().strftime('%Y%m'))
    )
    consumption_year: Mapped[int] = mapped_column(
        db.Integer,
        server_default=text("(DATE_FORMAT(CURRENT_TIMESTAMP, '%Y') + 0)"),
        default=lambda: int(datetime.now().strftime('%Y'))
    )
    # 消费金额或次数
    amount_used: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True)
    # 消费后剩余金额或次数
    remaining_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True)
    # 卡包类型（综合卡：comprehensive，按次计费卡：per_use）
    card_type: Mapped[Optional[str]] = mapped_column(db.String(20), nullable=True)
    # 消费说明
    description: Mapped[Optional[str]] = mapped_column(db.Text)
    # 是否失效
    is_invalid: Mapped[bool] = mapped_column(db.Boolean, default=False)
    # 股东占比（记录当时的股东占比）
    equity_ratio: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True)
    # 记录创建时间
    created_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),
        default=datetime.utcnow
    )
    # 记录更新时间
    updated_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),
        default=datetime.utcnow,
        onupdate=datetime.utcnow
    )

    # 关联关系（不使用外键约束）
    store = relationship(
        'Store',
        primaryjoin='CardConsumption.store_id == Store.id',
        backref='card_consumptions',
        foreign_keys=[store_id]
    )
    card_package = relationship(
        'CardPackage',
        primaryjoin='CardConsumption.card_package_id == CardPackage.id',
        backref='consumptions',
        foreign_keys=[card_package_id]
    )
    user = relationship(
        'User',
        primaryjoin='CardConsumption.user_id == User.id',
        backref='card_consumptions',
        foreign_keys=[user_id]
    )
    staff = relationship(
        'User',
        primaryjoin='CardConsumption.staff_id == User.id',
        backref='card_sales',
        foreign_keys=[staff_id]
    )
    product = relationship(
        'Product',
        primaryjoin='CardConsumption.product_id == Product.id',
        backref='consumptions',
        foreign_keys=[product_id]
    )

    def __init__(self, transaction_type: int, staff_id: int, income_type: int = 0, store_id: Optional[int] = None,
                 card_package_id: Optional[int] = None, user_id: Optional[int] = None,
                 handle_user_id: Optional[int] = None, product_id: Optional[int] = None,
                 consumption_date: Optional[datetime] = None, amount_used: Optional[float] = None,
                 remaining_amount: Optional[float] = None, card_type: Optional[str] = None,
                 description: Optional[str] = None, order_id: Optional[int] = None,
                 equity_ratio: Optional[float] = None):
        self.transaction_type = transaction_type
        self.income_type = income_type
        self.staff_id = staff_id
        self.store_id = store_id
        self.card_package_id = card_package_id
        self.user_id = user_id
        self.product_id = product_id
        self.consumption_date = consumption_date
        self.amount_used = amount_used
        self.remaining_amount = remaining_amount
        self.card_type = card_type
        self.description = description
        self.order_id = order_id
        self.handle_user_id = handle_user_id
        self.equity_ratio = equity_ratio

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'order_id': self.order_id,  # 添加order_id到返回字典
            'income_type': self.income_type,
            'transaction_type': self.transaction_type,
            'store_id': self.store_id,
            'card_package_id': self.card_package_id,
            'user_id': self.user_id,
            'staff_id': self.staff_id,
            'product_id': self.product_id,
            'consumption_date': self.consumption_date.isoformat() if self.consumption_date else None,
            'consumption_day': self.consumption_day,
            'consumption_month': self.consumption_month,
            'consumption_year': self.consumption_year,
            'amount_used': self.amount_used,
            'remaining_amount': self.remaining_amount,
            'card_type': self.card_type,
            'description': self.description,
            'is_invalid': self.is_invalid,
            'equity_ratio': self.equity_ratio,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'handle_user_id': self.handle_user_id,
        }